#include <sharedMem.h>
#include <printThings.h>

struct sharedMem *smem = (struct sharedMem *)SHARED_MEM_START;

char sharedMemON = FALSE;
char updated = FALSE;

char isLocked(){
    return smem->locked;
}

char getCharInStdOutAtPosition(int pos){
    return smem->stdOut[pos];
}

int getStdOutPosition(){
    return smem->stdOutPos;
}

int getStdInPosition(){
    return smem->stdInPos;
}

char *getStdIn(){
    return (char *)&smem->stdIn;
}

void flushStdIn(){
    int i;
    for(i = 0; i < BUFFER_LEN; i++){
        smem->stdIn[i] = 0x0;
    }
    smem->stdInPos = 0;
}

void addCharToStdOut(char c){
    LOCK;

    smem->stdOut[smem->stdOutPos] = c;
    smem->stdOutPos++;

    UNLOCK;
}

void getPositionsFromSharedMem(int *posX, int *posY){
    if(sharedMemON == FALSE)
        return;

    if(updated == FALSE)
        return;

    *posX = smem->posX;
    *posY = smem->posY;
}

void updatePosXY(int posX, int posY){
    if(sharedMemON == FALSE)
        return;
    smem->posX = posX;
    smem->posY = posY;

    updated = TRUE;
}

char isSharedMemON(){
    return sharedMemON;
}

int getPosX(){
    return smem->posX; 
}

int getPosY(){
    return smem->posY;
}

void unlockSharedMem(){
    smem->locked = 0;
}

void initSharedMemory(){
    smem->locked = 1;

    smem->posX = smem->posY = smem->sek = smem->fileAdress = 0;
    smem->stdInPos = 0;
    smem->stdOutPos = 0;
    smem->clearScreen = FALSE;
    smem->cmdMax = 0;
 
    int i;

    for(i = 0; i < BUFFER_LEN; i++){
        smem->stdIn[i] = smem->stdOut[i] = 0x0;
    }
    
    sharedMemON = TRUE;
}

void addCmdToCommandQueue(int cmd){
    smem->cmdList[smem->cmdMax] = cmd;
    smem->cmdMax++;
}

char getClearScreen(){
    return smem->clearScreen;
}

void setClearScreen(char s){
    smem->clearScreen = s;
}

void addKeyToStdIn(char c){
    LOCK;

    smem->stdIn[smem->stdInPos] = c;
    addCharToStdOut(c);
    smem->stdInPos++;

    //UNLOCK;
}

int getPosXLOCK(){
    WAIT_UNTIL_UNLOCK
    return smem->posX;
}

int getPosYLOCK(){
    WAIT_UNTIL_UNLOCK
    return smem->posY;
}

void setPosX(int posX){
    smem->posX = posX;
}

void setPosY(int posY){
    smem->posY= posY;
}

